package com.cyw.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyw.pojo.User;
import com.cyw.service.IUserService;
import com.cyw.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cyw
 * @since 2022-10-30
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private IUserService service;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation(value = "登录接口",notes = "登录接口的说明")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",//参数名字
                    value = "用户名",//参数的描述
                    required = true,//是否必须传入
                    paramType = "query" //paramType定义参数传递类型：有path,query,body,form,header
            )
            ,
            @ApiImplicitParam(name = "password",//参数名字
                    value = "密码",//参数的描述
                    required = true,//是否必须传入
                    paramType = "query"
            )
    })
    @PostMapping(value = "/login")
    public Map<String,Object> login(String username, String password) throws UnsupportedEncodingException, JsonProcessingException {
        Map<String,Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", DigestUtils.md5DigestAsHex(password.getBytes("utf-8")));
        QueryWrapper qw = new QueryWrapper<User>();
        qw.allEq(map);
        User user = service.getOne(qw);
        Map<String,Object> res = new HashMap<>();
        res.put("errorCode", 0);
        if (user != null) {
            String token = DigestUtils.md5DigestAsHex(username.getBytes("utf-8"));
            res.put("token", token);
            res.put("msg", "登陆成功!");
            String objectJson = JSON.toJSONString(user);
            redisUtil.set(token, objectJson);
        } else {
            res.put("errorCode", -1);
            res.put("msg","用户名或密码错误！");
        }
        return res;
    }
}

